package com.hc.componentspringboot.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import javax.sql.DataSource;

/**
 * 自定义安全配置类
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private DataSource dataSource;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //----------------自定义用户认证方式-------------------
        //内存身份认证
//        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//        InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> memoryAuthentication = auth.inMemoryAuthentication();
//        memoryAuthentication.passwordEncoder(encoder);
//        memoryAuthentication
//                .withUser("tom")
//                .password(encoder.encode("123456"))
//                .roles("common")
//                .and().
//                withUser("lisi")
//                .password(encoder.encode("123456"))
//                .roles("vip");

        //JDBC身份认证
//        String sql = "select username,password,valid from t_customer where username=?";
//        String psql = "select c.username,a.authority from t_customer c,t_authority a,t_customer_authority ca where " +
//                      "ca.customer_id=c.id and ca.authority_id=a.id and c.username=?";
//        JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcAuthentication = auth.jdbcAuthentication();
//        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
//        jdbcAuthentication
//                .passwordEncoder(encoder)
//                .dataSource(dataSource)
//                .usersByUsernameQuery(sql)
//                .authoritiesByUsernameQuery(psql);

        //UserDetailsService身份认证
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        auth.userDetailsService(userDetailsService).passwordEncoder(encoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //---------------------自定义用户权限管理--------------------
        http.authorizeRequests()
                .antMatchers("/")
                .permitAll()
                .antMatchers("/login/**").permitAll()
                .antMatchers("/detail/common/**").hasRole("common")
                .antMatchers("/detail/vip/**").hasRole("vip")
                .anyRequest().authenticated();
//                .and()
//                .formLogin();

        //自定义用户登录控制
        http.formLogin()
                .loginPage("/userLogin").permitAll()
                .usernameParameter("name").passwordParameter("pwd")
                .defaultSuccessUrl("/")
                .failureUrl("/userLogin?error");

        //自定义用户退出登录
        http.logout()
                .logoutUrl("/mylogout")
                .logoutSuccessUrl("/userLogin");

        //记住我 基于简单加密token实现
//        http.rememberMe()
//                .rememberMeParameter("remeberme")
//                .tokenValiditySeconds(2000);

        //记住我 基于持久化实现
        http.rememberMe()
                .rememberMeParameter("remeberme")
                .tokenValiditySeconds(2000)
                .tokenRepository(generateRepository());

        //自定义跨站请求
//        http.csrf().disable();
    }

    @Bean
    public JdbcTokenRepositoryImpl generateRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    }
}
